﻿package com.thorqq.magictimer.db;

import java.util.ArrayList;
import java.util.List;

import com.thorqq.magictimer.download.TaskInfo;
import com.thorqq.magictimer.download.ThreadInfo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.SparseArray;

public class DownloadDBhelper
{    
    private SQLiteOpenHelper mOpenHelper;
    private static Context mContext;
                    
    private DownloadDBhelper(){}
    
    private static DownloadDBhelper mDao = new DownloadDBhelper();

    public static DownloadDBhelper getIntance()
    {        
        return getIntance(mContext);
    }

    public static DownloadDBhelper getIntance(Context context)
    {        
        mContext = context;
        if(mDao == null)
        {
            mDao = new DownloadDBhelper();
        }
        return mDao;
    }
    
    public static void initialize(Context context)
    {        
        mContext = context;
        mDao = new DownloadDBhelper();
    }    

    private static class DatabaseHelper extends SQLiteOpenHelper {
        
        private static final int DATABASE_VERSION = 1;
        private static final String DATABASE_NAME = "downloadInfo.db";  
        
        public DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("create table IF NOT EXISTS thread_info(" +
            		"task_id        integer, " +
            		"thread_id      integer, " + 
            		"start_pos      integer, " +
            		"end_pos        integer, " +
            		"compelete_size integer)");

            db.execSQL("create table IF NOT EXISTS task_info(" +
            		"task_id        integer, " +
            		"file_size      integer, " +
            		"completed_size integer, " +
                    "create_time    integer, " +
                    "auto_install   integer, " +
            		"url_string     varchar, " +
            		"local_file     varchar)");

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int currentVersion) {
        }
    }
    
    public void open()
    {  
        mOpenHelper = new DatabaseHelper(mContext);
    }  
    
    public void close()
    {  
        mOpenHelper.close();
        mOpenHelper = null;
    }
        
    private void closeCur(Cursor cur)
    {
        if(cur != null)
        {
            cur.close();
        }
    }

    private int genTaskid()
    {
        //递增序列
        Cursor cur = null;
        SQLiteDatabase database = mOpenHelper.getReadableDatabase();
        try
        {
            //SparseArray<TaskInfo> 存储的数值都是按键值从小到大的顺序排列好的
            //所以这些产生的是最小的taskid
            String sql = "select min(task_id) from task_info";
            cur = database.rawQuery(sql, null);  
            if(cur.moveToNext())
            {
                return cur.getInt(0) - 1;
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            closeCur(cur);
            database.close();
        }

        return 0;
    }
    
    public SparseArray<TaskInfo> getTasks()
    {
        SparseArray<TaskInfo> list = new SparseArray<TaskInfo>();
        SQLiteDatabase database = mOpenHelper.getReadableDatabase();
        Cursor cur = null;
        try
        {
            String sql = "select task_id, file_size, completed_size, create_time, " +
            		"auto_install, url_string, local_file from task_info";
            cur = database.rawQuery(sql, null);
            while (cur.moveToNext())
            {
                TaskInfo info = new TaskInfo(cur.getInt(0), cur.getInt(1),
                        cur.getInt(2), cur.getLong(3), cur.getInt(4), 
                        cur.getString(5), cur.getString(6));
                list.put(info.getTaskid(), info);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            closeCur(cur);
            database.close();
        }
        return list;
    }

    
    public void insertTaskInfo(TaskInfo info)
    {
        info.setTaskid(genTaskid());
        
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            
            deleteTaskInfo(db, info.getTaskid());
            
            ContentValues cv = new ContentValues();
            cv.put("task_id",         info.getTaskid());
            cv.put("file_size",       info.getFileSize());
            cv.put("completed_size",  info.getComplete());
            cv.put("create_time",     info.getCreateTime());
            cv.put("auto_install",    info.getAutoInstall());
            cv.put("url_string",      info.getUrlstring());
            cv.put("local_file",      info.getLocalFile());
            db.insert("task_info", null, cv);         

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }
    
    public void updateTaskInfo(int taskid, int fileSize, int completedSize)
    {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            
            String sql = "update task_info set file_size=?, completed_size=? where task_id=?";
            Object[] bindArgs = { fileSize, completedSize, taskid };
            db.execSQL(sql, bindArgs);

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }
    
    public void deleteTaskInfo(int taskid)
    {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            
            deleteTaskInfo(db, taskid);

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }
    
    private void deleteTaskInfo(SQLiteDatabase db, int taskid)
    {
        db.delete("task_info", "task_id=?", new String[] { ""+taskid });
    }


    /**
     * 保存 下载的具体信息
     */
    public void saveThreadInfo(List<ThreadInfo> infos)
    {
        if(infos.size() == 0)
        {
            return;
        }
        
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            //先删
            deleteThreadInfo(db, infos.get(0).getTaskid());
            //后插
            for (ThreadInfo info : infos)
            {
                String sql = "insert into thread_info(task_id, thread_id,start_pos, end_pos,compelete_size) values (?,?,?,?,?)";
                Object[] bindArgs = { info.getTaskid() ,info.getThreadId(), info.getStartPos(), info.getEndPos(),
                        info.getCompeleteSize()};
                db.execSQL(sql, bindArgs);
            }

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 得到下载具体信息
     */
    public List<ThreadInfo> getThreadInfo(int taskid)
    {
        List<ThreadInfo> list = new ArrayList<ThreadInfo>();
        SQLiteDatabase database = mOpenHelper.getReadableDatabase();
        Cursor cur = null;
        try
        {
            String sql = "select task_id, thread_id, start_pos, end_pos,compelete_size from thread_info where task_id=?";
            cur = database.rawQuery(sql, new String[] { ""+taskid });
            while (cur.moveToNext())
            {
                ThreadInfo info = new ThreadInfo(cur.getInt(0), cur.getInt(1),
                        cur.getInt(2), cur.getInt(3), cur.getInt(4));
                list.add(info);
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            closeCur(cur);
            database.close();
        }
        return list;
        
    }

    /**
     * 更新数据库中的下载信息
     */
    public void updataInfos(int taskid, int threadId, int compeleteSize)
    {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            
            String sql = "update thread_info set compelete_size=? where thread_id=? and task_id=?";
            Object[] bindArgs = { compeleteSize, threadId, taskid };
            db.execSQL(sql, bindArgs);

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 下载完成后删除数据库中的数据
     */
    public void deleteThreadInfo(int taskid)
    {
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        try
        {
            db.beginTransaction();
            
            deleteThreadInfo(db, taskid);

            db.setTransactionSuccessful();
        } 
        catch(Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            db.endTransaction();
            db.close();
        }
    }
    
    private void deleteThreadInfo(SQLiteDatabase db, int taskid)
    {
        db.delete("thread_info", "task_id=?", new String[] { ""+taskid });
    }

}
